import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from './routers'
import store from '@/store'
Vue.use(VueRouter)
Vue.use(store)
//重写push和replace方法，解决编程式导航产生的报错问题（多次点击search，报错）对程序无影响，只是会报错
let originPush = VueRouter.prototype.push;
let originhReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originhReplace.call(this, location, resolve, reject);
    } else {
        originhReplace.call(this, location, () => { }, () => { })
    }
}
let router = new VueRouter({
    mode: 'history',
    routes,
    //页面跳转之后滚动条置顶
    scrollBehavior(to, from, savedPosition) {
        return { y: 0 }
    }
})
//全局守卫：前置守卫
router.beforeEach(async (to, from, next) => {
    //next:放行函数 next()放行
    //next('/login')放行到login
    //next();
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name
    if (token) {
        if (to.path == '/login') {
            next('/home')
        } else {
            if (name) {
                next();
            } else {
                try {
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    //token失效了
                    //清除token，跳转到login
                    await store.dispatch('userLogout');
                    next('login')
                }
            }
        }
    } else {
        //用户未登录，全部放行，暂时没弄
        next()
    }
})
export default router;